<?php
namespace app\admin\controller;

use think\Request;
use think\Config;
use think\Cache;
use think\Validate;

class Link extends Base
{
	/*
	 *	列表
	*/
	public function index()
	{
		$list = \think\Db::table('d_links')->order('sort ASC')->select();;

			// dd($list);
		$menu = self::getMenuArr();

		return view('index', compact('list', 'menu'));
	}

	/*
	 *	添加
	*/
	public function add()
	{
		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	            ['icon', 'require', '请输入ICO'],
	            ['url', 'require', '请输入链接'],
	            ['name', 'require', '请输入链接名称'],
	            ['sort', 'require', '请输入排序'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }

	        $res = \think\Db::table('d_links')->insert($data);

	        if(!$res){
	        	return error('添加失败');
	        }
	        logger(2, "新增链接");

	        return success(['url'=>"/admin/link/index"], '添加成功');
		} 

		$menu = self::getMenuArr();

		return view('add', compact('menu'));
	}

	/*
	 *	添加分类
	*/
	public function edit()
	{
		$id = $this->request->param('id');
		$detail = \think\Db::table('d_links')->where('id', $id)->find();

		if(Request::instance()->isPost()){
			$data = $this->request->param();
			// dd($data);
	        $validate = new Validate([
	           	['icon', 'require', '请输入ICO'],
	            ['url', 'require', '请输入链接'],
	            ['name', 'require', '请输入链接名称'],
	            ['sort', 'require', '请输入排序'],
	        ]);
	        if (!$validate->check($data)) {
	            return error($validate->getError());
	        }
	        
	        $res =  \think\Db::table('d_links')->where('id', $data['id'])->update($data);

	        if($res || $res == false){
	        	logger(2, "编辑link信息");

	        	return success(['url'=>"/admin/link/index"], '更新成功');

	        }

	        return error('更新失败');
		}

		$menu = self::getMenuArr();

		return view('edit', compact('detail', 'menu'));
	}

	/*
	 *	删除分类
	*/
	public function del()
	{
		$id = $this->request->param('id');
		if(empty($id)){
			return error('参数有误');
		}

		$res =  \think\Db::table('d_links')->where('id', $id)->delete();

		if(!$res){
			return error('删除失败');
		}

		logger(2, "删除link链接");

		return success(1, '删除成功');

	}
	
}
